using System.Collections.Generic;
using System.Text;

namespace OracleInternal.SqlAndPlsqlParser.LocalParsing
{
	internal class OracleLpSubqueryFactoringTerm : OracleLpStatementDataContainer
	{
		protected bool m_vNamedObjectReferencesRetrieved;

		protected OracleLpColumnMappedQueryName m_vColumnMappedQueryName;

		private OracleLpSubquery m_vSubquery;

		protected List<OracleLpColumnDescriptor> m_vColumnDescriptors;

		internal override OracleLpStatementElementType ElementType => OracleLpStatementElementType.SubqueryFactoringTerm;

		public OracleLpColumnMappedQueryName ColumnMappedQueryName
		{
			get
			{
				return m_vColumnMappedQueryName;
			}
			set
			{
				m_vColumnMappedQueryName = value;
			}
		}

		internal OracleLpSubquery Subquery
		{
			get
			{
				return m_vSubquery;
			}
			set
			{
				m_vSubquery = value;
				if (m_vSubquery != null)
				{
					m_vSubquery.Parent = this;
				}
			}
		}

		public override List<OracleLpColumnDescriptor> ColumnDescriptors
		{
			get
			{
				if (m_vColumnDescriptors == null)
				{
					Resolve();
				}
				return m_vColumnDescriptors;
			}
		}

		public OracleLpSubqueryFactoringTerm(OracleLpStatementElement parent)
			: base(parent)
		{
		}

		public override void Resolve()
		{
			m_vColumnDescriptors = m_vSubquery.ColumnDescriptors;
			if (m_vColumnMappedQueryName != null && m_vColumnMappedQueryName.ColumnAliases != null)
			{
				for (int i = 0; i < m_vColumnDescriptors.Count; i++)
				{
					OracleLpColumnDescriptor oracleLpColumnDescriptor = m_vColumnDescriptors[i];
					oracleLpColumnDescriptor.ColumnName = m_vColumnMappedQueryName.ColumnAliases[i];
					oracleLpColumnDescriptor.IsAliased = true;
				}
			}
		}

		public override void RetrieveNamedObjectReferences(OracleLpStatement statement)
		{
			if (!m_vNamedObjectReferencesRetrieved)
			{
				m_vNamedObjectReferencesRetrieved = true;
				m_vSubquery.RetrieveNamedObjectReferences(statement);
			}
		}

		internal override void ToString(StringBuilder sb)
		{
			string depthIndent = base.DepthIndent;
			sb.Append(depthIndent);
			sb.Append("Term: ");
			sb.Append(m_vColumnMappedQueryName.Name.DbName);
			if (m_vColumnMappedQueryName.ColumnAliases != null)
			{
				foreach (OracleLpName columnAlias in m_vColumnMappedQueryName.ColumnAliases)
				{
					sb.Append(" ,col: ");
					sb.Append(columnAlias.DbName);
				}
			}
			sb.Append("\n");
		}
	}
}
